var app = getApp()
//常量数据配置
var ConstantData = require('../../../common/constant_data.js')
var common = require("../../../common/common.js")
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowFee:false,
    isShowInfo:false,
    locations:[],
    userUseRecord:'',
    costRecord:[],
    page_show:false,
    payStatus:true,
    alertBoxStatus:false,
    noLoginFlg:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
 async onLoad(options) {
    let that=this
    let orderData=JSON.parse(decodeURIComponent(options.data)) 
    if (typeof orderData.consumePrice == 'number') {
      orderData.consumePrice = orderData.consumePrice.toString().split('.')
    }
    console.log('传递参数',orderData,options.data)
    that.setData({
      orderData:orderData
    })
  //  await that.getNetwork()
  //  await that.getOrderDetail(orderData.orderCode)
  },
  /**
   * 监听网络状态
   */
  getNetwork: function () {
    var that = this;
    wx.getNetworkType({
      success: function (res) {
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        let networkType = res.networkType
        that.setData({
          networkType: networkType
        })
      }
    })
    if (wx.onNetworkStatusChange){
      wx.onNetworkStatusChange(function (res) {
        console.log(res)
        let networkType = res.networkType
        let isConnected = res.isConnected
        that.setData({
          networkType: networkType,
          isConnected: isConnected
        })
        if (isConnected) {
          that.getOrderDetail(that.data.orderData.orderCode)
        }
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
 async onShow() {
    let that =this
    await that.getNetwork()
    await that.getOrderDetail(that.data.orderData.orderCode)
    that.getLocations()
  },
  //获取可归还位置
  getLocations() {
    let that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_hospital/info',
        method: 'post',
        header: header,
        data: {
          equId: that.data.orderData.equipmentId
        },
        success(res) {
          let locationList = res.data;
          if (!locationList) {
            wx.showToast({
              title: '查找失败',
              icon: 'none'
            })
            return;
          }
          if (locationList.chairList && locationList.chairList.length > 0) { //轮椅
            if (locationList.chairList.length > 2) {
              that.setData({
                getMoreShow: true,
                locations: locationList.chairList.slice(0, 2),
                hospitalName: locationList.basicInfo.hospitalName
              })
            } else {
              that.setData({
                locations: locationList.chairList,
                hospitalName: locationList.basicInfo.hospitalName
              })
            }
          } else { //担架
            if (locationList.carList.length > 2) {
              that.setData({
                getMoreShow: true,
                locations: locationList.carList.slice(0, 2),
                hospitalName: locationList.basicInfo.hospitalName
              })
            } else {
              that.setData({
                locations: locationList.carList,
                hospitalName: locationList.basicInfo.hospitalName
              })
            }
          }
          if (that.data.locations) {
            that.data.locations.forEach(item => {
              var countsA = item.pileList.filter(item1 => item1.equipCode && item1.equipCode != 0).length;
              item.countsA = countsA;
              item.countsB = item.pileList.length - countsA;
            })
            that.setData({
              locations: that.data.locations,
            })
          }
        }
      })
    })
  },
  //获取详情信息
  getOrderDetail:function(orderCode) {
    let that =this
    if(app.globalData.loginData && app.globalData.loginData.nophone == 1) {
      //需要重新登录      
      this.setData({
        noLoginFlg: true
      })
      return
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + `/lease/recordDetail/${orderCode}`,
        method: 'get',
        header: header,
        success: function (res) {
          console.log("userRecordsList-->", res);
          if (res.data.result == 0) {
            if (typeof res.data.data.userUseRecord.consumePrice == 'number') {
              res.data.data.userUseRecord.consumePrice = res.data.data.userUseRecord.consumePrice.toString().split('.')
            }
            if (typeof res.data.data.userUseRecord.consumeCash == 'number') {
              res.data.data.userUseRecord.consumeCash = res.data.data.userUseRecord.consumeCash.toString().split('.')
            }
         that.setData({
          page_show:true,
          costRecord:res.data.data.costRecord,
          userUseRecord:res.data.data.userUseRecord
         })
          } else {
            wx.showToast({
              title: '获取失败'
            })
          }
        },
        complete() {
          getApp().hideLoading()
        }
      })
    })        
  },
    //打开租借费用
    openCosts:function(){
      this.setData({
        isShowFee:!this.data.isShowFee,
      })
    },
    //打开租借信息
    openInfo:function(){
      this.setData({
        isShowInfo:!this.data.isShowInfo,
      })
    },
  /**
   * 客服中心
   */
  toService: function () {
    wx.switchTab({
      url: '/pages/servicer/index'
    })
  },
  /**
   * 故障上报
   */
  tofault: function () {
    wx.navigateTo({
      url: '/pkgNew/pages/faultReporting/index',
    })
  },
  //归还轮椅
  toNoBackTip: function () {
    wx.navigateTo({
      url: '/pages/index/no_back_tip/no_back_tip?equId=' + this.data.orderData.equipmentId + "&hospitalName=" + this.data.orderData.tiName + '&positions=' + this.data.orderData.positions + '&pt=user_lease' + '&equType=' + this.data.orderData.equType + "&orderCode=" +this.data.orderData.orderCode,
    })
  },
  //支付租金
  toPayLease:function(event) {
    var orderCode = event.currentTarget.dataset.ordercode
    this.toPay(orderCode)
  },
  toPay: function (orderCode) {
    var that = this
    if (that.data.payStatus) {
    }else {
      console.log("支付中。。。。")
      return
    }
    that.setData({
       payStatus:false
    })
    console.log("去支付。。。" + orderCode)

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/unpay/payment',
        method: 'post',
        header: header,
        data: {
          ordernum: orderCode
        },
        success: function (res) {
          var data = res.data
          console.log("支付结果---" + data.result)
          if (data.result == 0) {
            that.setData({
              alertBoxStatus: true,
              msg: data.description,
            })
            that.getOrderDetail(orderCode)
            console.log("刷新支付记录")
          } else if (data.result == -1) {
            console.log("开始微信支付")
            that.toPayOrder(orderCode)
          } else {
            that.setData({
              alertBoxStatus: true,
              msg: data.description
            })
          }

        },
        complete: function (res) {
          console.log("恢复支付")
          that.setData({
            payStatus: true
          })
        }
      })

    })
    
  },
  toPayOrder: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function(loginCode, orderCode, err){
 
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              console.log("租金支付失败----result=" + data.result + ",description=" + data.description)
              that.setData({
                msg: data.description ? data.description:"支付失败",
                alertBoxStatus: true
              })
              return
            }
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res);   
                that.getOrderDetail(orderCode)              
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'ulea-' + JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          },
          complete: function (res) {
            console.log("恢复支付。。。") 
            that.setData({
              payStatus: true
            })
          }
        })
      })
    });
  },
  sureTip:function() {
    this.setData({
      alertBoxStatus:false
    })
  },
  // 位置详情
  toLocationDetail: function (e) {
    console.log('toLocationDetail-->', e);
    e.currentTarget.dataset.data['hosname']=e.currentTarget.dataset.hosname
    e.currentTarget.dataset.data['categoryName']=e.currentTarget.dataset.categoryname
    let locationItem = e.currentTarget.dataset.data;
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/locations/locationDetail/locationDetail?locationDetail=' + JSON.stringify(locationItem)
    })
  },
    /**
   * 去退押金
   */
  toRefundDeposit: function () {
    wx.navigateTo({
      url: '/pages/user_record/deposit/user_deposit',
    })
  },
    //查看收费规则
    toFeeRule(){
      wx.navigateTo({
        url: '/pkgNew/pages/feeRule/index?selectOrder='+`${this.data.orderData?encodeURIComponent(JSON.stringify(this.data.orderData)):''}`+`&noLoginFlg=${this.data.noLoginFlg}`,
      })
    },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})